(function($) {
	var TFO = {
		slideMenu: function() {
			var menu = this.$sidebarMenu,
				that = this;
			var animationSpeed = 300;
			var nice = menu.niceScroll({
				horizrailenabled: false
			})
			menu.on('click', 'li a', function(e) {
				var $this = $(this);
				var checkElement = $this.next();
				if (checkElement.is('.treeview-menu') && checkElement.is(':visible')) {
					checkElement.slideUp(animationSpeed, function() {
						checkElement.removeClass('menu-open');
						nice.resize();
					});
					checkElement.parent("li").removeClass("active");
				} else if ((checkElement.is('.treeview-menu')) && (!checkElement.is(':visible'))) {
					var parent = $this.parents('ul').first();
					var ul = parent.find('ul:visible').slideUp(animationSpeed);
					ul.removeClass('menu-open');
					var parent_li = $this.parent("li");
					checkElement.slideDown(animationSpeed, function() {
						checkElement.addClass('menu-open');
						parent.find('li.active').removeClass('active');
						parent_li.addClass('active');
						nice.resize();
					});
				};
				if (checkElement.is('.treeview-menu')) {
					e.preventDefault();
				};

				if (that.setting.tabList) {
					return false;
				}
			});
		},
		tab: function() {
			var that = this,
				menu = this.$sidebarMenu.find(".treeview-menu li a")
			that.$tabList.off("click", "a.main");
			that.$tabLeft.off("click");
			that.$tabRight.off("click");
			this.initTab();
			if (that.setting.tabList) {
				menu.off("click").on("click", function() {
					that.tabOpen(this.href, $.trim(this.text), $(this).attr("data-id"))
					return false;
				});
			}
		},
		getMenuList: function() {
			var that = this;
			$.ajax({
				url: that.setting.menuApi,
				suc: function(data) {
					$.each(data[that.setting.menuDataField], function(index, obj) {
						if (obj[that.setting.menuPidKey] == "-1") {
							that.$sidebarMenu.append($("<li>", {
								"class": "treeview"
							}).append($("<a>", {
								href: obj[that.setting.menuUrlKey] || null,
								"target": TFO.setting.tabList ? '' : 'main-iframe'
							}).on("click", function() {
								if ($(this).attr("href") && $(this).attr("target") == "main-iframe") {
									window.location.hash = '//' + obj[that.setting.menuIdKey] + '//' + encodeURI(obj[that.setting.menuUrlKey])
								}
							}).html('<i class="' + (obj[that.setting.menuIconKey] || "fa fa-files-o") + '"></i> <span>' + obj[that.setting.menuNameKey] + '</span> <i class="fa fa-angle-right pull-right"></i>')).append($("<ul>", {
								"class": "treeview-menu",
								"data-id": obj[that.setting.menuIdKey]
							})));
						} else {
							var $ul = that.$sidebarMenu.find("ul.treeview-menu[data-id=" + obj[that.setting.menuPidKey] + "]");
							//$ul.append($("<li>").html('<a data-id="'+obj[that.setting.menuIdKey]+'" href="'+(obj[that.setting.menuUrlKey] || "#")+'" '+(TFO.setting.tabList ? '' : 'target="main-iframe"')+'><i class="'+(obj[that.setting.menuIconKey] || "fa fa-files-o")+'"></i> '+obj[that.setting.menuNameKey]+'</a>'))
							var $a = $("<a>", {
								"data-id": obj[that.setting.menuIdKey],
								"href": obj[that.setting.menuUrlKey] || "#",
								"target": TFO.setting.tabList ? '' : 'main-iframe'
							}).append('<i class="' + (obj[that.setting.menuIconKey] || "fa fa-files-o") + '"></i> ' + obj[that.setting.menuNameKey]);
							$ul.append($("<li>").append($a));
							if (!TFO.setting.tabList) {
								if (location.hash && location.hash.split("//").length >= 3 && obj[that.setting.menuIdKey] == location.hash.split("//")[1]) {
									$a.addClass("active");
									if (TFO.setting.menuPosition == "left") {
										$a.parents(".treeview").trigger("click");
									}
								}
								$a.on("click", function() {
									window.location.hash = '//' + obj[that.setting.menuIdKey] + '//' + encodeURI(obj[that.setting.menuUrlKey]);
								})
							}
						}
					})
					if (that.setting.menuPosition == "left") {
						that.slideMenu()
					} else {
						that.$sidebarMenu.find("ul.treeview-menu").each(function() {
							if ($(this).find("li").length == 0) {
								$(this).remove();
							} else {
								/*
								var $a = $(this).siblings("a"),that = this;
								if(!$a.attr("href")){
									var l = $(this).find("a:eq(0)")
									$a.attr({"href":l.attr("href"),"data-id":l.attr("data-id")}).on("click",function(){
										$(that).find("a:eq(0)").addClass("active").trigger("click")
									})
								}
								*/
							}
						})
					}

					//上部通栏菜单
					if (that.setting.menuPosition == "top" && that.setting.topMenuFullView) {
						that.$sidebar.addClass("fullview")
						//子菜单左边距位置算法
						function subMenuPostion() {
							that.$sidebar.find("ul.treeview-menu").css("paddingLeft", that.$sidebar.find("li.treeview:eq(0)").position().left)
						}
						subMenuPostion();
						$(window).on("resize", subMenuPostion)
					}
					that.tab()
					if (that.setting.menuLoaded && $.isFunction(that.setting.menuLoaded)) {
						that.setting.menuLoaded(data)
					}
				},
				hasAlert: true,
				loadingContainer: that.$sidebarMenu
			});
		},

		scrollSetp: 500, //menu左右按钮每次滑动的像素
		operationWidth: 200, //menu操作按钮的总宽度
		leftOperationWidth: 40, //左侧按钮的宽度
		animatSpeed: 150, //切换动画速度
		linkframe: function(url, value, id) {
			var that = this;
			if (this.$tabContent.find("iframe.active").attr) {
				this.$tabList.find("a.active").removeClass("active")
				this.$tabList.find("a[data-url='" + url + "'][data-title='" + value + "']").addClass("active")
				this.$tabContent.find("iframe.active").removeClass("active").removeClass("in");
				var $current = this.$tabContent.find(".iframe-content[data-url='" + url + "'][data-title='" + value + "']").addClass("active")
				setTimeout(function() {
					$current.addClass("in")
				})
			}
			if (id) {
				that.$sidebarMenu.find(".active").removeClass("active");
				var li = that.$sidebarMenu.find("a[data-id=" + id + "]").addClass("active").parents("li.treeview")
				if (li.find("ul.treeview-menu").is(':hidden')) {
					li.children("a").trigger("click")
				} else {
					li.addClass("active")
				}
			}
		},
		move: function($tab) {
			var that = this;
			var nav = that.$tabList;
			var releft = $tab.offset().left - that.$sidebar.width();
			var wwidth = parseInt($("#page-tab").width());
			var left = parseInt(nav.css("margin-left"));
			if (releft < 0 && releft <= wwidth) {
				nav.animate({
					"margin-left": (left - releft + leftOperationWidth) + "px"
				}, animatSpeed);
			} else if (releft + $tab.width() > wwidth - that.operationWidth) {
				nav.animate({
					"margin-left": (left - releft + wwidth - $tab.width() - operationWidth) + "px"
				}, animatSpeed);
			}
		},
		createmove: function() {
			var that = this;
			var nav = that.$tabList;
			var wwidth = parseInt(that.$tabs.width());
			var navwidth = parseInt(nav.width());

			if (wwidth - that.operationWidth < navwidth) {
				nav.animate({
					"margin-left": "-" + (navwidth - wwidth + that.operationWidth) + "px"
				}, that.animatSpeed);
			}
		},
		closemenu: function(event) {
			var that = this;
			$(event.target.parentElement).animate({
				"width": "0",
				"padding": "0"
			}, 0, function() {
				var $this = $(this);
				if ($this.hasClass("active")) {
					var linext = $this.next();
					if (linext.length > 0) {
						linext.trigger("click");
						that.move(linext);
					} else {
						var liprev = $this.prev();
						if (liprev.length > 0) {
							liprev.trigger("click")
							that.move(liprev);
						}
					}
				}
				$this.remove();
				that.$tabContent.find(".iframe-content[data-url='" + $this.attr("data-url") + "'][data-title='" + $this.attr("data-title") + "']").remove();
			});
			if (event) {
				event.stopPropagation();
			}
		},
		initTab: function() {
			var that = this;
			that.$tabList.on("click", "a.main", function() {
				var $this = $(this);
				that.linkframe($this.attr("data-url"), $this.attr("data-title"), "home");
			});
			that.$tabLeft.on("click", function() {

				var nav = that.$tabList;
				var left = parseInt(nav.css("margin-left"));

				if (left !== 0) {
					nav.animate({
						"margin-left": (left + that.scrollSetp > 0 ? 0 : (left + that.scrollSetp)) + "px"
					}, that.animatSpeed);
				}
			});
			that.$tabRight.on("click", function() {
				var nav = that.$tabList;
				var left = parseInt(nav.css("margin-left"));

				var wwidth = parseInt(that.$tabs.width());
				var navwidth = parseInt(nav.width());
				var allshowleft = -(navwidth - wwidth + that.operationWidth);
				if (allshowleft !== left && navwidth > wwidth - that.operationWidth) {
					var temp = (left - that.scrollSetp);
					nav.animate({
						"margin-left": (temp < allshowleft ? allshowleft : temp) + "px"
					}, that.animatSpeed);
				}
			});
		},
		tabOpen: function(linkUrl, linkHtml, linkId) {
			var that = this;
			var $tab = that.$tabList.find("a[data-url='" + linkUrl + "'][data-title='" + linkHtml + "'][data-id='" + linkId + "']");
			if ($tab.length === 0) {
				var $close = $("<span>", {
					"class": "glyphicon glyphicon-remove ml5"
				}).on("click", function(event) {
					that.closemenu(event)
				});
				$("<a>", {
					"data-url": linkUrl,
					"data-title": linkHtml,
					"data-id": linkId
				}).html(linkHtml).on("click", function() {
					that.linkframe($(this).attr("data-url"), $(this).attr("data-title"), $(this).attr("data-id"));
				}).append($close).appendTo(that.$tabList);
				$("<iframe>", {
					"class": "iframe-content",
					"data-url": linkUrl,
					"data-title": linkHtml,
					"src": linkUrl
				}).appendTo(that.$tabContent);
				that.createmove();
			} else {
				that.move($tab);
			}
			that.linkframe(linkUrl, linkHtml, linkId);
		},
		tabClose: function() {
			var that = this;
			that.$tabList.find("a.active").animate({
				width: "0px",
				padding: "0px"
			}, 0, function() {
				var $this = $(this);
				var linext = $this.next();
				if (linext.length > 0) {
					linext.trigger("click");
					that.move(linext);
				} else {
					var liprev = $this.prev();
					if (liprev.length > 0) {
						liprev.trigger("click")
						that.move(liprev);
					}
				}
				$(this).remove();
				that.$tabContent.find(".iframe-content[data-url='" + $this.attr("data-url") + "'][data-title='" + $this.attr("data-title") + "']").remove();

			});
		},
		tabCloseAll: function() {
			var that = this;
			that.$tabList.find("a:not(.main) span").each(function() {
				$(this).trigger("click")
			})
			that.$tabList.css({
				marginLeft: "0px"
			})
		},
		tabCloseOther: function() {
			var that = this;
			that.$tabList.find("a:not(.main):not(.active) span").each(function() {
				$(this).trigger("click")
			})
			that.$tabList.css({
				marginLeft: "0px"
			})
		},
		initHtml: function(data) {
			var that = this;
			//生成html
			this.$header = $("<div>", {
					"class": "tabFrame-header"
				}).appendTo($("body")),
				this.$container = $("<div>", {
					"class": "tabFrame-container"
				}).appendTo($("body"))
			this.$logo = $("<div>", {
					"class": "pull-left"
				}).append($("<div>", {
					"class": "text-middle tabFrame-logo"
				}).append(this.setting.logoImgUrl ? $("<img>", {
					"src": this.setting.logoImgUrl,
					"alt": "logo",
					"title": "logo"
				}) : "")).appendTo(this.$header),
				this.$userInfo = $("<div>", {
					"class": "tabFrame-userinfo pull-right pr30"
				})
				.append("欢迎 ")
				.append($("<span>", {
					"class": "tabFrame-role mr5"
				}).html(data[that.setting.userInfoRoleNameKey]))
				.append($("<span>", {
					"class": "tabFrame-user mr5"
				}).html(data[that.setting.userInfoUserNameKey]))
				//.append($("<a>",{"class":"tabFrame-logout","href":this.setting.logoutUrl}).html("[退出]"))
				.appendTo(this.$header);
			var $setting = $("<span>", {
				"class": "tabFrame-setting dropdown mr5"
			}).appendTo(this.$userInfo);
			var $settingBtn = $("<a>", {
					"href": "#",
					"class": "dropdown-toggle",
					"data-toggle": "dropdown",
					"aria-expanded": "false"
				})
				.appendTo($setting)
				.append($("<span>", {
					"class": "name"
				}).html("设置"))
				.append($("<span>", {
					"class": "caret"
				}))
			this.$settingUl = $("<ul>", {
				"class": "dropdown-menu dropdown-menu-right",
				"role": "menu",
				"aria-labelledby": "dropdownMenu1"
			}).appendTo($setting)

			$("<li>", {
				role: "presentation"
			}).append($("<a>", {
				"class": "my-info",
				href: "#",
				role: "menuitem",
				tabindex: "-1"
			}).on("click", function() {
				if ($('#settingPortal')) {
					$('#settingPortal').modal();
				} else {
					return false;
				}
			}).html("个人信息")).appendTo(that.$settingUl);
			$("<li>", {
				role: "presentation"
			}).append($("<a>", {
				"class": "help",
				href: "#",
				role: "menuitem",
				tabindex: "-1"
			}).on("click", function() {
				if ($('#settingHelp')) {
					$('#settingHelp').modal();
				} else {
					return false;
				}
			}).html("帮助")).appendTo(that.$settingUl)
			$("<li>", {
				role: "presentation"
			}).append($("<a>", {
				"class": "about",
				href: "#",
				role: "menuitem",
				tabindex: "-1"
			}).on("click", function() {
				if ($('#settingAboutUs')) {
					$('#settingAboutUs').modal();
				} else {
					return false;
				}
			}).html("关于系统")).appendTo(that.$settingUl);

			$('<li role="separator" class="divider"></li>').appendTo(that.$settingUl);
			$("<li>", {
				role: "presentation"
			}).append($("<a>", {
				href: this.setting.logoutUrl,
				role: "menuitem",
				tabindex: "-1"
			}).on("click", function() {

			}).html("退出")).appendTo(that.$settingUl)

			if (this.setting.menuPosition == "left") {
				this.$sidebar = $("<div>", {
					"class": "tabFrame-sidebar pull-left"
				}).appendTo(this.$container);
				this.$sidebarMenu = $("<ul>", {
					"class": "tabFrame-sidebar-menu"
				}).appendTo(this.$sidebar);
				this.$content = $("<div>", {
					"class": "tabFrame-content"
				}).appendTo(this.$container);
			} else if (this.setting.menuPosition == "top") {
				this.$sidebar = $("<div>", {
					"class": "tabFrame-nav"
				}).appendTo(this.$header.addClass("dark-bg has-shadow"))
				this.$sidebarMenu = $("<ul>", {
					"class": "tabFrame-top-nav"
				}).appendTo(this.$sidebar);
				this.$content = $("<div>", {
					"class": "tabFrame-content no-sidebar"
				}).appendTo(this.$container);
			}
			if (TFO.setting.tabList) {
				this.$tabs = $("<div>", {
					"class": "tabFrame-tabs has-shadow"
				}).appendTo(this.$content);
			} else {
				that.$sidebarMenu.on("click", "a[target=main-iframe]", function() {
					that.$sidebarMenu.find("a[target=main-iframe]").removeClass("active")
					$(this).addClass("active")
				})
			}

			this.$tabContent = $("<div>", {
					"class": "tabFrame-tab-content " + (TFO.setting.tabList ? "" : "no-tab")
				}).appendTo(this.$content),
				//this.$footer = $("<div>",{"class":"tabFrame-footer text-center"}).html(this.setting.copyrightText).appendTo(this.$content);

				this.$tabLeft = $("<div>", {
					"class": "tabFrame-tab-left"
				}).append($("<span>", {
					"class": "glyphicon glyphicon-backward"
				})).appendTo(this.$tabs),
				this.$tabNav = $("<nav>", {
					"class": "tab-list"
				}).appendTo(this.$tabs)
			this.$tabList = $("<div>", {
				"class": "menu-list pos-abs"
			}).append($("<a>", {
				"class": "active main",
				"data-url": this.setting.homePageUrl,
				"data-title": this.setting.homePageTitle
			}).html(this.setting.homePageTitle)).appendTo(this.$tabNav)
			this.$tabRight = $("<div>", {
					"class": "tabFrame-tab-right"
				}).append($("<span>", {
					"class": "glyphicon glyphicon-forward"
				})).appendTo(this.$tabs),
				this.$tabClose = $("<div>", {
					"class": "tabFrame-tab-close dropdown"
				}).append($("<a>", {
						"class": "dropdown-toggle",
						"data-toggle": "dropdown",
						"aria-expanded": "false"
					})
					.append($("<span>", {
						"class": "name"
					}).html("关闭操作"))
					.append($("<span>", {
						"class": "caret"
					}))
				).appendTo(this.$tabs).on("click", "a.close-all-tabs", function(event) {
					that.tabCloseAll(event)
				}).on("click", ".close-other-tabs", function(event) {
					that.tabCloseOther(event)
				});

			var mainUrl = this.setting.homePageUrl;
			if (!this.setting.tabList && location.hash && location.hash.split("//").length >= 3) {
				var h = location.hash.split("//");
				mainUrl = h[2]
			}
			this.$mainIframe = $("<iframe>", {
				"class": "iframe-content active main in",
				"name": "main-iframe",
				"src": mainUrl,
				"data-url": mainUrl,
				"data-title": this.setting.homePageTitle
			}).appendTo(this.$tabContent);
			this.$tabCloseList = $("<ul>", {
					"class": "dropdown-menu dropdown-menu-right",
					"role": "menu",
					"aria-labelledby": "dropdownMenu1"
				})
				.append($("<li>", {
					"role": "presentation"
				}).append($("<a>", {
					"class": "close-all-tabs",
					"role": "menuitem",
					"tabindex": "-1"
				}).html("关闭所有标签")))
				.append($("<li>", {
					"role": "separator",
					"class": "divider"
				}))
				.append($("<li>", {
					"role": "presentation"
				}).append($("<a>", {
					"class": "close-other-tabs",
					"role": "menuitem",
					"tabindex": "-1"
				}).html("关闭其他标签")))
				.appendTo(this.$tabClose);
			this.getMenuList()
		}
	};
	jQuery.extend({
		tabFrame: function(options) {
			options = TFO.setting = $.extend({
				menuApi: "", //左侧菜单接口地址
				menuDataField: "rows", //左侧菜单接口数据字段
				menuIdKey: "id",
				menuNameKey: "name",
				menuPidKey: "pid",
				menuUrlKey: "url",
				menuIconKey: "icon",
				menuLoaded: function(data) {}, //菜单加载成功回调函数
				userInfoApi: "", //用户信息接口
				userInfoDataField: "", //用户信息接口数据字段
				userInfoRoleNameKey: "roleName", //角色名称字段
				userInfoUserNameKey: "userName", //用户名称字段
				userInfoLoaded: function(data) {}, //用户信息加载成功回调函数
				logoutUrl: "./logout", //登出地址
				loginUrl: "./login.html", //登录地址
				copyrightText: "", //版权信息文字
				logoImgUrl: "", //logo图片url
				homePageUrl: "main.html", //主页地址
				homePageTitle: "首页",
				tabList: true, //是否开启标签列表,
				menuPosition: "left", //菜单位置;可选：left,top。
				topMenuFullView: true, //上部下拉菜单通栏显示
			}, options)
			$.ajax({
				type: "get",
				url: options.userInfoApi,
				suc: function(data) {
					TFO.initHtml(options.userInfoDataField ? ($.isArray(data[options.userInfoDataField]) ? data[options.userInfoDataField][0] : data[options.userInfoDataField]) : data)
					if (options.userInfoLoaded && $.isFunction(options.userInfoLoaded)) {
						options.userInfoLoaded(data)
					}
				},
				err: function() {
					location.href = options.loginUrl
				},
				loadingContainer: $("body")
			});
		}
	})
	window.TFO = TFO;
	window.tabOpen = TFO.tabOpen;
	window.tabClose = TFO.tabClose;
})(jQuery);
